package com.realworld.service.Impl;

import com.realworld.common.R;
import com.realworld.mapper.UserInfoMapper;
import com.realworld.model.dto.UserInfoReq;
import com.realworld.model.pojo.UserInfo;
import com.realworld.service.UserInfoService;
import com.realworld.utils.JwtUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class UserInfoImpl implements UserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo login(UserInfoReq userInfoReq) {
        UserInfo userInfo = userInfoMapper.selectUserByUsername(userInfoReq.getUsername());
        if (Objects.isNull(userInfo)){
            R.error(4001,"该用户未注册！");
        }
        if (!userInfoReq.getPassword().equals(userInfo.getPassword()) || !userInfoReq.getUsername().equals(userInfo.getUsername())){
            R.error(4001,"账号或者密码错误！");
        }

        return userInfo;
    }

    @Override
    public R register(UserInfoReq userInfoReq) {
        userInfoReq.setNickname(userInfoReq.getUsername());
        UserInfo userInfo = userInfoMapper.selectUserByUsername(userInfoReq.getUsername());
        if (!Objects.isNull(userInfo)){
            R.error(4002,"用户名已存在！");
        }
        userInfoMapper.insertUser(userInfoReq);
        return R.ok(4001,"注册成功！");
    }

    @Override
    public UserInfo getUserInfo(String username) {
        UserInfo userInfo = userInfoMapper.selectUserByUsername(username);
        if (Objects.isNull(userInfo)){
            R.error(4001,"这种异常比较难出现！");
        }
        return userInfo;
    }

    @Override
    public R updateUserInfo(UserInfoReq userInfoReq) {
        int i = userInfoMapper.updateUserInfo(userInfoReq);
        if (i ==0 ){
            R.error(4001,"更新失败");
        }
        return R.ok(4002,"更新成功！");
    }
}
